#!/usr/bin/env python3
"""
record2csv.py
将 record.db3 中的所有表导出为同名的 CSV 文件
用法:
    python record2csv.py         # 默认数据库 record.db3
    python record2csv.py my.db3  # 指定数据库
"""

import sys
import pathlib
import sqlite3
import pandas as pd

def export_db_to_csv(db_path: pathlib.Path):
    """把数据库里的每张表导出成 CSV"""
    if not db_path.exists():
        print(f"❌ 找不到数据库文件: {db_path.resolve()}")
        sys.exit(1)

    conn = sqlite3.connect(db_path)
    # 读取所有表名
    tables = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'", conn)["name"]

    if tables.empty:
        print("⚠️  数据库里没有表，退出。")
        return

    for tbl in tables:
        df = pd.read_sql_query(f"SELECT * FROM [{tbl}]", conn)
        csv_file = db_path.with_name(f"{tbl}.csv")
        df.to_csv(csv_file, index=False, encoding="utf-8")
        print(f"✅ {tbl} -> {csv_file.name}  ({len(df)} 行)")

    conn.close()

if __name__ == "__main__":
    db_file = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else pathlib.Path("record.db3")
    # print(db_file)
    export_db_to_csv(db_file)
